package com.janj.jdbc2;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;

//数据删除

public class Demo2 {
    Connection conn = null;
    Statement stat = null;
    ResultSet resu = null;

    @Before
    public void start() {
        try {
            String url = "jdbc:mysql://192.168.65.47:3306/duod9";
            String username = "root";
            String password = "root";
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //定义删除数据的方法

    public int delteToDB(Integer id) {
        //DELETE FROM phone WHERE id = 8 ;

        int number = 0;

        try {
            //1.组装sql语句
            String sql = "DELETE FROM phone WHERE id =" + id;

            //2.获取执行者的对象
            Statement stat = conn.createStatement();

            //3.执行sql语句,返回结果
            number = stat.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return number;
    }

    //测试方法
    @Test
    public void testDelteToDB() {
        int num = delteToDB(8);
        System.out.println(num);
        System.out.println(num == 0 ? "删除失败" : "删除成功");
    }


    @After
    public void end() {
        if (resu != null) {
            try {
                resu.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


